import tracker from '../utils/tracker.js';
export default function injectXHR() {
  // 保存原始的 open 和 send 方法
  const originalXhrOpen = window.XMLHttpRequest.prototype.open;
  window.XMLHttpRequest.prototype.open = function (method, url, async) {
    // console.log("url", url)
    // 上报请求不需要返回
    if (!url.match(/logstores/) && !url.match(/sockjs/)) {
      // console.log("logstores")
      this.logData = {
        method,
        url,
        async,
        startTime: Date.now()
      };
    }
    return originalXhrOpen.apply(this, arguments);
  };
  const originalXhrSend = window.XMLHttpRequest.prototype.send;
  window.XMLHttpRequest.prototype.send = function (body) {
    if (this.logData) {
      const startTime = Date.now();
      const handler = (type) => (event) => {
        const duration = Date.now() - startTime;
        const status = this.status; // 状态码
        const statusText = this.response.error; // OK Server Error
        tracker.send({
          kind: 'stability',
          type: 'xhr',
          eventType: event.type,
          pathname: this.logData.url, // 请求路径
          status: `${status}-${statusText}`, // 状态码
          duration, // 持续时间
          response: JSON.stringify(this.response),
          requestData: body || '',
          params: this.logData.params, // 响应体
          timestamp: Date.now()
        });
      };

      this.addEventListener('load', handler('load'), false);
      this.addEventListener('error', handler('error'), false);
      this.addEventListener('abort', handler('abort'), false);
    }

    return originalXhrSend.apply(this, arguments);
  };
}